package com.sohoo.nio.data.upload;



public class HexUtils {
	
	 public  static String toHexString(byte res) {
		byte[] bytes= new byte[] {res};
		 return toHexString(bytes);
	 }
	
	/**根据二进制数组算出16进制的表示*/
	 public  static String toHexString(byte[] res) {
	        StringBuilder sb = new StringBuilder(res.length << 1);
	        for (int i = 0; i < res.length; i++) {
	            String digit = Integer.toHexString(0xFF & res[i]);
	            if (digit.length() == 1) {
	                sb.append('0');
	            }
	            sb.append(digit);
	        }
	        return sb.toString().toUpperCase();
	    }
	    /**
	     *会报异常
	     */
	    public  static byte[] toByteArray(String hexString) {
	        int arrLength = hexString.length() >> 1;
	        byte buff[] = new byte[arrLength];
	        for (int i = 0; i < arrLength; i++) {
	            int index = i << 1;
	            String digit = hexString.substring(index, index + 2);
	            buff[i] = (byte) Integer.parseInt(digit, 16);
	        }
	        return buff;
	    }
	    
	    /*计算16进制字符串的校验和,会自动去除空格**/
	    public static byte validateSum(String hexString) {
	    	hexString = hexString.replaceAll(" ", "");
			return validateSum(toByteArray(hexString));
	    }
	    /**用于计算校验和*/
	    public static byte validateSum(byte[] hex) {
	    	byte  result = 0;
	    	if(hex==null) return result;
	    	for(byte num : hex) {
	    		result+=num;
	    	}
			return result;
	    }
	    /**
	     * 将整个16进制数据进行减33处理
	     * */
	    public static String minus33(String hexString){
	    	StringBuilder result = new StringBuilder();
	    	 hexString = hexString.replaceAll(" ", "");
	    	int length = hexString.length();
	    	if(length%2!=0) return ""; 
	    	StringBuilder sb = new StringBuilder(hexString);
	    	for(int i =0;i<sb.length();i+=2) {
	    		char first = sb.charAt(i);
	    		char second = sb.charAt(2);
	    	char[] temp =	new char[] {first,second};
	    		Integer value = Integer.valueOf(new String(temp), 16);
	    		Integer minus = Integer.valueOf("33", 16);
	    		byte byteValue = Integer.valueOf(value-minus).byteValue();
	    		String resultValue = toHexString(byteValue);
	    		result.append(resultValue);
	    	}
	    	return result.toString();
	    }
	    
}
